package com.yao.club.service.impl;

import com.netease.yidun.sdk.core.utils.StringUtils;
import com.yao.club.entity.Topic;
import com.yao.club.entity.UserEntity;
import com.yao.club.entity.dto.*;
import com.yao.club.entity.request.CommentRequestEntity;
import com.yao.club.entity.request.PostsCreateRequestEntity;
import com.yao.club.entity.result.ResponseEntity;
import com.yao.club.entity.result.ResultEntity;
import com.yao.club.entity.vo.PostsCommentVO;
import com.yao.club.entity.vo.PostsInfoVO;
import com.yao.club.mapper.*;
import com.yao.club.reposittory.*;
import com.yao.club.service.PostsInfoService;
import com.yao.club.utils.ResponseUtils;
import org.apache.hc.core5.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PostsInfoServiceImpl implements PostsInfoService {

    @Resource
    PostsInfoMapper postInfoMapper;
    @Autowired
    SysImageRepository imageRepository;
    @Resource
    PostsTopicMapper topicMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    PostsCommentMapper postsCommentMapper;

    @Resource
    UserFollowMapper userFollowMapper;

    @Autowired
    PostsLikeRecordRepository postLikeRepository;
    @Autowired
    PostsCollectRecordRepository postsCollectRepository;
    @Autowired
    PostsShareRecordRepository postsShareRepository;
    @Autowired
    PostsShieldRecordRepository postsShieldRepository;
    @Autowired
    PostsInfoRepository postsInfoRepository;
    /**
     * 校验帖子
     * @param postsId
     * @return
     */
    @Override
    public ResponseEntity<Boolean> giveValidationLike(String postsId){
        PostsInfoVO postsInfoEntity = postInfoMapper.select(postsId);
        if(postsInfoEntity == null){
            return ResponseUtils.failed("帖子失效");
        }

        return ResponseUtils.success(true);
    }

    /**
     * 根据id获得帖子详情
     * @param postsId
     * @return
     */
    @Override
    public ResponseEntity<PostsInfoVO> getByPostsId(String postsId){
        PostsInfoVO postsInfoEntity = postInfoMapper.select(postsId);
        if (postsInfoEntity == null){
            return ResponseUtils.failed("帖子失效");
        }
        if (!TextUtils.isEmpty(postsInfoEntity.img_ids)){
            String[] ids = postsInfoEntity.img_ids.split(",");
            List<SysImg> images = new ArrayList<>();
            for (String  id: ids) {
                images.add(imageRepository.selectById(id));
            }
            postsInfoEntity.image = images;
        }
        if (!TextUtils.isEmpty(postsInfoEntity.topic_ids)){
            String[] ids = postsInfoEntity.topic_ids.split(",");
            List<Topic> topics = new ArrayList<>();
            for (String  id: ids) {
                topics.add(topicMapper.selectById(id));
            }
            postsInfoEntity.topics = topics;
        }

        return ResponseUtils.success(postsInfoEntity);
    }

    /**
     * 分页获得帖子评论信息
     */
    @Override
    public ResponseEntity<ResultEntity> pageComment(String postsId, int pageNum, int pageSize){
        ResultEntity postsCommentEntity = new ResultEntity();

        int total = postsCommentMapper.countCommentsByPostsId(postsId);
        postsCommentEntity.total = total;
        postsCommentEntity.size = pageSize;
        postsCommentEntity.current = pageNum;
        postsCommentEntity.records = getCommentsByPostsId(postsId);
        return ResponseUtils.success(postsCommentEntity);
    }
    @Override
    public List<PostsCommentVO> getCommentsByPostsId(String postsId) {
        // 获取一级评论
        List<PostsCommentVO> firstLevelComments = postsCommentMapper.selectFirstLevelComments(postsId);

        // 为每个一级评论获取二级评论
        firstLevelComments.forEach(comment -> {
            // 获取二级评论
            List<PostsCommentVO> secondLevelComments = postsCommentMapper.selectSecondLevelComments(comment.posts_comment_id);

            // 设置头像信息
            if (comment.head_img_id != null) {
                SysImg headImg = postsCommentMapper.selectHeadImgById(comment.head_img_id);
                comment.headImg = headImg;
            }

            // 为二级评论设置头像信息
            secondLevelComments.forEach(subComment -> {
                if (subComment.head_img_id!= null) {
                    SysImg headImg = postsCommentMapper.selectHeadImgById(subComment.head_img_id);
                    subComment.headImg = headImg;
                }
            });

            comment.twoLevel = secondLevelComments;
        });

        return firstLevelComments;
    }


    /**
     * 发布评论
     * @param request
     * @param username
     * @return
     */
    @Override
    public ResponseEntity<Boolean> addComment(CommentRequestEntity request,String username) {

        UserEntity currentUser = userMapper.select(username);
        // 构建评论实体
        PostsCommentVO comment = new PostsCommentVO();
        comment.setPosts_id(request.getPostsId());
        comment.setFirst_comment_id("0"); // 一级评论first_comment_id为0
        comment.setParent_id("0"); // 一级评论parent_id为0
        comment.setContent(request.getContent());
        comment.setCreate_by(currentUser.getMember_id()+"");
        comment.setCreate_name(currentUser.getNickname());
        comment.setHead_img_id(currentUser.getAvatar_id()+"");
        comment.setLevel(1); // 一级评论

        // 敏感词过滤
        comment.setIf_sensitive(true);
        PostsInfoVO postsInfoEntity = postInfoMapper.select(request.getPostsId());
        comment.setBe_reply_id(postsInfoEntity.create_by);

        UserEntity userEntity = userMapper.getUserByMemberId(postsInfoEntity.create_by);
        comment.setReply_name(userEntity.nickname);
        // 保存到数据库
        //posts_id,first_comment_id,parent_id,content,create_by,create_name,head_img_id,level,if_sensitive,create_time
        postsCommentMapper.addComment(comment.posts_id,comment.first_comment_id,comment.parent_id,comment.content,comment.create_by,comment.create_name,comment.head_img_id,comment.level,comment.if_sensitive,comment.reply_name,comment.be_reply_id);

        // 更新帖子评论数
        postInfoMapper.incrementCommentCount(request.getPostsId());

        return ResponseUtils.success(true);

    }

    /**
     * 发布评论
     * @param commentRequest
     * @param username
     * @return
     */
    @Override
    public ResponseEntity<Boolean> replyComment(CommentRequestEntity commentRequest,String username) {
        UserEntity currentUser = userMapper.select(username);
        // 构建评论实体
        PostsCommentVO reply = new PostsCommentVO();
        reply.setPosts_id(commentRequest.getPostsId());
        reply.setParent_id(commentRequest.getParentId());
        reply.setContent(commentRequest.getContent());
        reply.setCreate_by(currentUser.getMember_id()+"");
        reply.setCreate_name(currentUser.getNickname());
        reply.setHead_img_id(currentUser.getAvatar_id()+"");
        reply.setLevel(2); // 二级评论

        // 设置被回复人信息
        if (StringUtils.isNotEmpty(commentRequest.getBeReplyId())) {
            reply.setBe_reply_id(commentRequest.getBeReplyId());
            UserEntity beReplyUser = userMapper.getUserByMemberId(commentRequest.getBeReplyId());
            reply.setReply_name(beReplyUser.getNickname());
        }

        // 设置一级评论ID
        if (StringUtils.isNotEmpty(commentRequest.getFirstCommentId())) {
            reply.setFirst_comment_id(commentRequest.getFirstCommentId());
        }
        // 敏感词过滤
        reply.setIf_sensitive(true);
        // 保存到数据库
        postsCommentMapper.addComment(reply.posts_id,reply.first_comment_id,reply.parent_id,reply.content,reply.create_by,reply.create_name,reply.head_img_id,reply.level,reply.if_sensitive,reply.reply_name,reply.be_reply_id);
        // 更新一级评论的评论数
        postInfoMapper.incrementCommentCount(commentRequest.getPostsId());
        return ResponseUtils.success(true);
    }

    /**
     * 点赞帖子
     * @param postsId
     * @param username
     * **/
    @Override
    public ResponseEntity<Boolean> giveLike(Long postsId, String username) {
        UserEntity user = userMapper.select(username);
        PostsLikeRecord existingLike = postLikeRepository.findByPostIdAndUserId(postsId, user.getMember_id()+"");

        if (existingLike != null) {
            // 已点赞，执行取消点赞
            postLikeRepository.delete(existingLike);
            postInfoMapper.unIncrementLikeCount(postsId);
            return ResponseUtils.success(true);
        } else {
            // 未点赞，执行点赞
            PostsLikeRecord like = new PostsLikeRecord();
            like.setPostId(postsId);
            like.setUserId(user.member_id);
            like.setCreatedAt(Instant.now());
            postLikeRepository.save(like);
            postInfoMapper.incrementLikeCount(postsId);
            return ResponseUtils.success(true);
        }
    }

    /**
     * 收藏贴子
     * @param postsId
     * @param username
     * **/
    @Override
    public ResponseEntity<Boolean> giveCollect(Long postsId, String username) {
        UserEntity user = userMapper.select(username);
        PostsCollectRecord existingPost = postsCollectRepository.findByPostIdAndUserId(postsId, user.getMember_id()+"");

        if (existingPost != null) {
            postsCollectRepository.delete(existingPost);
            postInfoMapper.unIncrementCollectCount(postsId);
            return ResponseUtils.success(true);
        } else {
            PostsCollectRecord collect = new PostsCollectRecord();
            collect.setPostId(postsId);
            collect.setUserId(user.member_id);
            collect.setCreatedAt(Instant.now());
            postsCollectRepository.save(collect);
            postInfoMapper.incrementCollectCount(postsId);
            return ResponseUtils.success(true);
        }
    }

    /**
     * 分享贴子
     * @param postsId
     * @param username
     * **/
    @Override
    public ResponseEntity<Boolean> giveShare(Long postsId, String username,String share_type) {
        UserEntity user = userMapper.select(username);
        PostsShareRecord share = new PostsShareRecord();
        share.setPostId(postsId);
        share.setUserId(user.member_id);
        share.setShareType(share_type);
        share.setCreatedAt(Instant.now());
        postsShareRepository.save(share);
        postInfoMapper.incrementShareCount(postsId);
        return ResponseUtils.success(true);

    }

    /**
     * 屏蔽贴子
     * @param postsId
     * @param username
     * **/
    @Override
    public ResponseEntity<Boolean> shield(Long postsId, String username) {
        UserEntity user = userMapper.select(username);
        PostsShieldRecord existingPost = postsShieldRepository.findByPostIdAndUserId(postsId, user.getMember_id()+"");
        if (existingPost != null) {
            return ResponseUtils.failed("帖子之前屏蔽过");
        } else {
            PostsShieldRecord shield = new PostsShieldRecord();
            shield.setPostId(postsId);
            shield.setUserId(user.member_id);
            shield.setCreatedAt(Instant.now());
            postsShieldRepository.save(shield);
            return ResponseUtils.success(true);
        }
    }
 /**
     * 分页查询帖子列表
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param sortType 排序类型
     * @param username 当前登录用户（可能为null）
     * @return 帖子列表结果
     */
    @Override
    public ResponseEntity<ResultEntity<PostsInfoVO>> pageList(String topicId, String keyword, Integer pageNum, Integer pageSize, String sortType, String memberId,Integer isFocus, String username) {
        try {
            ResultEntity result = new ResultEntity<PostsInfoVO>();
            String userId = null;

            // 如果用户已登录，获取用户ID
            if (StringUtils.isNotEmpty(username)) {
                UserEntity user = userMapper.select(username);
                if (user != null) {
                    userId = user.getMember_id() + "";
                }
            }

            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 获取帖子总数和分页数据
            List<PostsInfoVO> posts;
            int total;

            if (userId != null) {
                // 登录用户 - 排除屏蔽的帖子
                if (StringUtils.isNotEmpty(topicId)) {//根据话题搜索
                    total = postInfoMapper.countTopicPostsExcludeShielded(topicId, userId);
                    posts = postInfoMapper.pageTopicPostsExcludeShielded(topicId, userId, offset, pageSize, sortType);
                }else if (StringUtils.isNotEmpty(keyword)){//根据关键字搜索
                    total = postInfoMapper.countSearchPostsExcludeShielded(keyword, userId);
                    posts = postInfoMapper.searchPostsExcludeShielded(keyword, userId, offset, pageSize);
                }else if (StringUtils.isNotEmpty(memberId)){//根据用户id搜索
                    total = postInfoMapper.countSearchPostsMemberIdExcludeShielded(memberId, userId);
                    posts = postInfoMapper.searchPostsMemberIdExcludeShielded(memberId, userId, offset, pageSize);
                } else if (isFocus != null && isFocus == 1) {//获取关注用户的帖子信息
                    total = postInfoMapper.countFollowingPostsExcludeShielded(userId);
                    posts = postInfoMapper.pageFollowingPostsExcludeShielded(userId, offset, pageSize);
                }  else{
                    total = postInfoMapper.countPostsExcludeShielded(userId);
                    posts = postInfoMapper.pagePostsExcludeShielded(userId, offset, pageSize, sortType);
                }

            } else {
                // 未登录用户 - 显示所有未删除的帖子
                if (StringUtils.isNotEmpty(topicId)) {
                    total = postInfoMapper.countTopicAllValidPosts(topicId);
                    posts = postInfoMapper.pageTopicAllValidPosts(topicId, offset, pageSize, sortType);
                }else if (StringUtils.isNotEmpty(keyword)){//根据关键字搜索
                    total = postInfoMapper.countSearchAllValidPosts(keyword);
                    posts = postInfoMapper.searchAllValidPosts(keyword, offset, pageSize);
                }else if (StringUtils.isNotEmpty(memberId)){//根据用户id搜索
                    total = postInfoMapper.countSearchAllValidPostsByMemberId(memberId);
                    posts = postInfoMapper.searchAllValidPostsByMemberId(memberId, offset, pageSize);
                }else{
                    total = postInfoMapper.countAllValidPosts();
                    posts = postInfoMapper.pageAllValidPosts(offset, pageSize, sortType);

                }
            }

            // 处理每个帖子的详细信息
            if (posts != null && !posts.isEmpty()) {
                for (PostsInfoVO post : posts) {
                    // 处理图片
                    if (StringUtils.isNotEmpty(post.getImg_ids())) {
                        String[] ids = post.getImg_ids().split(",");
                        List<SysImg> images = new ArrayList<>();
                        for (String id : ids) {
                            SysImg image = imageRepository.selectById(id);
                            if (image != null) {
                                images.add(image);
                            }
                        }
                        post.setImage(images);
                    }
                    //处理头像
                    if (StringUtils.isNotEmpty(post.getCreate_by())) {
                        UserEntity userEntity = userMapper.getUserByMemberId(post.create_by);
                        SysImg userImg = imageRepository.selectById(userEntity.avatar_id+"");
                        post.setAvatar(userImg);
                    }

                    // 处理话题
                    if (StringUtils.isNotEmpty(post.getTopic_ids())) {
                        String[] ids = post.getTopic_ids().split(",");
                        List<Topic> topics = new ArrayList<>();
                        for (String id : ids) {
                            Topic topic = topicMapper.selectById(id);
                            if (topic != null) {
                                topics.add(topic);
                            }
                        }
                        post.setTopics(topics);
                    }

                    // 如果是登录用户，设置互动状态
                    if (userId != null) {
                        // 设置是否点赞
                        PostsLikeRecord likeRecord = postLikeRepository.findByPostIdAndUserId(Long.parseLong(post.getPosts_id()), userId);
                        post.setIf_like(likeRecord != null ? 1:0);

                        // 设置是否收藏
                        PostsCollectRecord collectRecord = postsCollectRepository.findByPostIdAndUserId(Long.parseLong(post.getPosts_id()), userId);
                        post.setIf_collect(collectRecord != null ? 1:0);
                       // 添加用户关系判断
                       int relationStatus = checkUserRelation(userId, post.getCreate_by());
                       post.setRelation(relationStatus);

                        boolean isSelfPost = userId.equals(post.getCreate_by());
                        post.setIf_my(isSelfPost ? 1:0);
                    }else {
                        // 未登录用户，设置为无关系
                        post.setRelation(0);
                        post.setIf_my(0);
                    }
                }
            }

            // 设置分页结果
            result.setRecords(posts);
            result.setTotal(total);
            result.setSize(pageSize);
            result.setCurrent(pageNum);
            result.setPages((total + pageSize - 1) / pageSize); // 计算总页数

            return ResponseUtils.success(result);

        } catch (Exception e) {
            return ResponseUtils.failed("查询帖子列表失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户关系
     * @param currentUserId 当前登录用户ID
     * @param authorId 帖子作者ID
     * @return 关系类型 (0:无关系 1:粉丝 2:已关注 3:相互关注)
     */
    private int checkUserRelation(String currentUserId, String authorId) {
        // 检查当前用户是否关注了作者
        boolean isFollowing = userFollowMapper.checkFollowStatus(currentUserId, authorId);

        // 检查作者是否关注了当前用户
        boolean isFollowed = userFollowMapper.checkFollowStatus(authorId, currentUserId);

        if (isFollowing && isFollowed) {
            return 3; // 相互关注
        } else if (isFollowing) {
            return 2; // 已关注
        } else if (isFollowed) {
            return 1; // 粉丝
        } else {
            return 0; // 无关系
        }
    }

    /**
     * 发布帖子
     */
    @Override
    public ResponseEntity<Boolean> createPost(PostsCreateRequestEntity request, String username) {
        try {
            // 获取当前用户信息
            UserEntity user = userMapper.select(username);
            if (user == null) {
                return ResponseUtils.failed("用户不存在");
            }
          
            // 验证图片是否存在
            if (StringUtils.isNotEmpty(request.getImgIds())) {
                String[] imgIds = request.getImgIds().split(",");
                for (String imgId : imgIds) {
                    SysImg image = imageRepository.selectById(imgId);
                    if (image == null) {
                        return ResponseUtils.failed("图片不存在：" + imgId);
                    }
                }
            }
            // 创建帖子实体
            PostsInfo post = new PostsInfo();
            post.setImgIds(request.getImgIds());
            post.setIfVideo(request.isIfVideo());

            post.setContent(request.getContent());
            post.setTopicIds(request.getTopicIds());
            post.setLocation(request.getLocation());
            post.setLon(request.getLongitude());
            post.setLat(request.getLatitude());

            // 设置基本信息
            post.setUserId(user.getMember_id()+"");
            post.setCreateBy(user.getMember_id() + "");
            post.setCreateTime(new Date());
            post.setUpdateTime(new Date());
            post.setDelFlag(0); // 0表示未删除

            // 初始化计数
            post.setLikeNumber(0);
            post.setCommentNumber(0);
            post.setCollectNumber(0);
            post.setShareNumber(0);

            // 生成帖子ID（使用雪花算法或其他方式）
            post.setPostsId(Long.parseLong(generatePostId()));
            // 验证话题是否存在（如果有话题）
            if (StringUtils.isNotEmpty(request.getTopicIds())) {
                String[] topicIds = request.getTopicIds().split(",");
                for (String topicId : topicIds) {
                    Topic topic = topicMapper.selectById(topicId);
                    if (topic == null) {
                        return ResponseUtils.failed("话题不存在：" + topicId);
                    }
                }
            }

            // 保存帖子
            PostsInfo save = postsInfoRepository.save(post);

            if (save != null) {
                // 更新话题的帖子数量
//                if (StringUtils.isNotEmpty(request.getTopicIds())) {
//                    String[] topicIds = request.getTopicIds().split(",");
//                    for (String topicId : topicIds) {
//                        topicMapper.incrementPostCount(topicId);
//                    }
//                }

                return ResponseUtils.success(true);
            } else {
                return ResponseUtils.failed("发布失败");
            }

        } catch (Exception e) {
            return ResponseUtils.failed("发布失败：" + e.getMessage());
        }
    }

    /**
     * 生成帖子ID
     */
    private String generatePostId() {
        // 这里使用简单的时间戳+随机数方式
        // 实际应用中建议使用雪花算法或其他分布式ID生成方案
        return System.currentTimeMillis() + "" + (int)((Math.random() * 9 + 1) * 100000);
    }
}
